//
//  WLRouterBlackDeviceController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/18.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterBlackDeviceController.h"
#import "WLBlackDeviceCell.h"
//#import "WLBlackDeviceModel.h"
#import "WLRouterDeviceModel.h"
#import "UIScrollView+EmptyDataSet.h"

@interface WLRouterBlackDeviceController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>//,RouterSocketDelegate>

@property (nonatomic, strong) UITableView   *tbDevices;
@property (nonatomic, strong) NSMutableArray    *arrDevices;
@property (nonatomic, assign) NSInteger     pageDevices;

@end

@implementation WLRouterBlackDeviceController

- (void)dealloc
{
//    [[WLSocketManager sharedSocketManager] removeDelegate:self];
    [[WLSocketManager sharedSocketManager] removeDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"黑名单管理";
    
    _arrDevices = [[NSMutableArray alloc] init];
    _tbDevices = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbDevices.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tbDevices.delegate = self;
    _tbDevices.dataSource = self;
    _tbDevices.rowHeight = WLScaleX(80);
    _tbDevices.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbDevices.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbDevices];
    WLWkSelf
    [_tbDevices mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    self.tbDevices.emptyDataSetSource = self;
    self.tbDevices.emptyDataSetDelegate = self;
//    _tbDevices.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
//        weakSelf.tbDevices.mj_footer = nil;
//        weakSelf.pageDevices = 1;
//        [weakSelf reqBlackDevices];
//    }];
    
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self receiveRouterBlacks];
//    [self reqBlackDevices];
}

//- (void)addFooterRefresh
//{
//    WLWkSelf
//    _tbDevices.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf reqBlackDevices];
//    }];
//}

- (void)receiveRouterBlacks
{
    NSDictionary *dict = @{@"type":@"DEVICE_BLACKLIST_REQ",@"content":@""};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    if ([msgModel.type isEqualToString:@"DEVICE_BLACKLIST_REP"])
    {
        if (msgModel.content != nil) {
//            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
//            NSError *err;
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                                options:NSJSONReadingMutableContainers
//                                                                  error:&err];
            self.arrDevices = [WLRouterDeviceModel mj_objectArrayWithKeyValuesArray:msgModel.content];
            [self.tbDevices reloadData];
        }
    }
    else if ([msgModel.type isEqualToString:@"COMMON_SUCCESS"])
    {
        [self showHUDMessage:@"设置成功"];
        [self receiveRouterBlacks];
    }
}
/*
- (void)reqBlackDevices
{
    NSDictionary *conditions = @{};
    NSDictionary *pages = @{@"page":@(_pageDevices),@"num":@10};
    NSDictionary *params = @{@"conditions":conditions,@"page":pages};
    WLWkSelf
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"black/list" withParamsDic:params success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbDevices.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.pageDevices==1)
        {
            [strongSelf.arrDevices removeAllObjects];
            if (productCount>10)
            {
                [strongSelf addFooterRefresh];
            }
        }
        NSArray *arrPros = [WLBlackDeviceModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrDevices addObjectsFromArray:arrPros];
            if (strongSelf.arrDevices.count >= productCount) {
                [strongSelf.tbDevices.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbDevices.mj_footer endRefreshing];
            }
        }
        else
        {
            [strongSelf.tbDevices.mj_footer endRefreshingWithNoMoreData];
        }
        [strongSelf.tbDevices reloadData];
        strongSelf.pageDevices += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tbDevices.mj_header endRefreshing];
        [weakSelf.tbDevices.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tbDevices.mj_header endRefreshing];
        [weakSelf.tbDevices.mj_footer endRefreshing];
    } inView:(_pageDevices==1&&_tbDevices.mj_header.isRefreshing==NO)?self.view:nil];
}
*/
#pragma mark - UITableView
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"移除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        WLLog(@"跟进");
//    }];
//
////    UITableViewRowAction *rowActionSec = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"快速备忘" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
////        WLLog(@"快速备忘");
////    }];
//    rowAction.backgroundColor = wlRedColor;
//    return @[rowAction];
//}

-  (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"移除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
//    WLWkSelf
//    WLBlackDeviceModel *model = self.arrDevices[indexPath.row];
//    NSDictionary *paramsp = @{@"id":@(model.numId)};
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"black/edit" withParamsDic:paramsp success:^(NSDictionary *successDict) {
//        [weakSelf.arrDevices removeObjectAtIndex:indexPath.row];
//        [weakSelf.tbDevices deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
//    } error:^(NSError *error) {
//
//    } inView:self.view];
    
    WLRouterDeviceModel *model = self.arrDevices[indexPath.row];
    NSDictionary *dictLast = @{@"name":model.name,@"macAddress":model.macAddress};
    NSString *dictStr = dictLast.mj_JSONString;
//    NSString *dictStr = model.mj_JSONString;
    NSDictionary *dict = @{@"type":@"DEVICE_BLACKREMOVE_SET",@"content":dictStr};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.arrDevices.count==0) {
        return 0;
    }
    return WLScaleX(20);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrDevices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strRouters = @"routersCell";
    WLBlackDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:strRouters];
    if (!cell) {
        cell = [[WLBlackDeviceCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strRouters];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    WLRouterDeviceModel *deviceModel = self.arrDevices[indexPath.row];
    cell.labTitle.text = deviceModel.name;
    cell.labDetail.text = [NSString stringWithFormat:@"MAC:%@",deviceModel.macAddress];
//    cell.labTime.text = [WLCommonTool strToLoginTime:deviceModel.loginTime];;
    
    return cell;
}

#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_data"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"这里什么都没有呢~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
